package com.lgb.controller.admin;

import com.lgb.Service.PicturesService;
import com.lgb.pojo.Pictures;
import com.lgb.utils.FileUtils;
import com.lgb.vo.BlogQuery;
import com.lgb.vo.PicturesQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.Date;

@Controller
@RequestMapping("/admin")
public class PicturesController {

    @Autowired
    private PicturesService picturesService;

    //转跳到图片上传页面
    @RequestMapping("/pictures_upload")
    public String pictures_load(){
        return "/admin/pictures_upload";
    }

    //接收传递而来的图片集并上传
    @PostMapping("/pictures_save")
    public String savepictures(MultipartFile[] pictures , String title , String description , RedirectAttributes redirectAttributes){
        FileUtils.saveMultiFile("C:\\Users\\86137\\Desktop\\blog\\src\\main\\resources\\static\\pictures", pictures);
        Pictures pictures1 = new Pictures();
        //设置标题
        pictures1.setName(title);
        //设置描述信息
        pictures1.setDescription(description);
        //设置更新时间
        pictures1.setUpdateTime(new Date());
        //设置文件路径
        String address = "C:\\Users\\86137\\Desktop\\blog\\src\\main\\resources\\static\\pictures\\" + FileUtils.findCommonDirectory(pictures);
        pictures1.setAddress(address);
        //保存到数据库
        picturesService.savePictures(pictures1);
        redirectAttributes.addFlashAttribute("message" , "新增成功");
        return "redirect:/admin/pictures_manage";
    }

    //转跳到图片管理页面
    @RequestMapping("/pictures_manage")
    public String picture_manage(Model model){
        model.addAttribute("pictures" , picturesService.getAllPictures());
        model.addAttribute("picturequerys" , picturesService.getAllPicturesQuery());
        return "/admin/pictures_manage";
    }

    //删除图片
    @GetMapping("/pictures_delete/{id}")
    public String picture_delete(@PathVariable Long id , RedirectAttributes redirectAttributes){
        picturesService.deletePictures(id);
        redirectAttributes.addFlashAttribute("message" , "删除成功") ;
        return "redirect:/admin/pictures_manage";
    }
}
